package com.example.ddz.framework.impl;

/**
 * Created by IntelliJ IDEA.
 * User: Marcel Melzig
 * Date: 19.07.11
 * Time: 19:59
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.res.AssetManager;
import android.os.Environment;

import com.example.ddz.framework.IFileIO;

public class AndroidFileIO implements IFileIO
{
    private final AssetManager assets;
    private final String externalStoragePath;

    /**
     * Creates an instance of the AndroidFileIO class.
     *
     * @param assets The asset manager handles the operations on the assets folder.
     */
    public AndroidFileIO(AssetManager assets)
    {
        this.assets = assets;
        this.externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    }

    /**
     * Reads a file from the assets folder.
     *
     * @param fileName The path of the asset.
     * @return An input stream of a file in the assets folder.
     * @throws IOException Will be thrown if the file couldn't be read.
     */
    @Override
    public InputStream ReadAsset(String fileName) throws IOException
    {
        return assets.open(fileName);
    }

    /**
     * Reads a file from the external storage.
     *
     * @param fileName The path of a file on the external storage.
     * @return A stream of a file on the external storage.
     * @throws IOException will be thrown if the file couldn't be read.
     */
    @Override
    public InputStream ReadFile(String fileName) throws IOException
    {
        return new FileInputStream(externalStoragePath + fileName);
    }

    /**
     * Writes a filestream to a path on the external storage.
     *
     * @param fileName A path on the external storage.
     * @return An output stream to a path on the external storage.
     * @throws IOException Will be thrown if the it can't be written to the given path.
     */
    @Override
    public OutputStream WriteFile(String fileName) throws IOException
    {
        return new FileOutputStream(externalStoragePath + fileName);
    }
}
